package com.vast.ui.component.socketinterface.server;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.net.Socket;

import com.vast.ui.component.socketinterface.request.Request;
import com.vast.ui.component.socketinterface.request.RequestQueue;
import com.vast.ui.component.state.Sequence;
import com.vast.ui.component.util.ConsoleLoggerSingleton;
import com.vast.ui.component.util.Logger;

public class SendHandler  implements Runnable {
	private final String        pluginId;
    private Socket              clientSendSocket;
    private DataOutputStream	out;
	private final Sequence      sequence;
	private final RequestQueue  sendQueue;
	private final Logger        logger;
	
	public SendHandler(String pluginId, Socket clientSendSocket, Sequence sequence, RequestQueue sendQueue) {
		this.pluginId         = pluginId;
        this.clientSendSocket = clientSendSocket;
        this.sequence      = sequence;
        this.sendQueue     = sendQueue;
        this.logger        = ConsoleLoggerSingleton.getInstance();
    }
    
    public void run() {
        try {
          	out = new DataOutputStream(new BufferedOutputStream(clientSendSocket.getOutputStream()));
            while(sequence.isSendConnection()) {
            	Request request = null;
            	try {	
            		request = sendQueue.getRequest();
            	} catch (Exception e) {
            		logger.writeEntry("getRequest() is interrupted");
            	}
            	if(request != null) {
            		int sizeOfData = request.data.length;
            		out.writeInt(sizeOfData);
            		out.writeInt(request.command);
            		out.write(request.data, 8, request.data.length - 8);
            		logger.writeEntry("out bufer size: " + out.size());
            		out.flush();
            	}
            	    	//Thread.sleep(5);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
            	clientSendSocket.close();
            	logger.writeEntry(pluginId + ": Exit Send Handler.");
            } catch (Exception e) {}
        }
    }
}
